package com.caiheng.api.controller.platform;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.estate.Estate;
import com.caiheng.api.entity.platform.PlatformPay;
import com.caiheng.api.entity.platform.WxPayTransaction;
import com.caiheng.api.entity.setmeal.SetMeal;
import com.caiheng.api.entity.setmeal.SetMealInfo;
import com.caiheng.api.entity.setmeal.SetMealInfoGivenRecord;
import com.caiheng.api.entity.setmeal.SetMealOrder;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.pay.utils.RSA;
import com.caiheng.api.pay.wxpay.WXPayCommonUtil;
import com.caiheng.api.pay.wxpay.WxAppPay;
import com.caiheng.api.service.estate.EstateService;
import com.caiheng.api.service.platfom.ParameterService;
import com.caiheng.api.service.platfom.PlatformPayService;
import com.caiheng.api.service.platfom.WxPayTransactionService;
import com.caiheng.api.service.platfom.WxTemplateService;
import com.caiheng.api.service.setmeal.SetMealInfoGivenRecordService;
import com.caiheng.api.service.setmeal.SetMealInfoService;
import com.caiheng.api.service.setmeal.SetMealOrderService;
import com.caiheng.api.service.setmeal.SetMealService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.DateUtil;
import com.caiheng.api.util.GsonResultBean;
import com.caiheng.api.util.OrderUtil;
import com.caiheng.api.util.Tools;
import com.vdurmont.emoji.EmojiParser;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@Author: ZhouWei
 *@Description:  小区相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/meal")//url:模块/资源/{}/细分
public class SetMealController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private SetMealService setMealService;
    @Resource
    private SetMealInfoService setMealInfoService;
    @Resource
    private SetMealOrderService mealOrderService;
    @Resource
    private SetMealInfoGivenRecordService mealInfoGivenRecordService;
    @Resource
    private EstateService estateService;
    @Resource
    private PlatformPayService platformPayService;
    @Resource
    private ParameterService parameterService;
    @Resource
    private WxPayTransactionService payTransactionService;
    @Resource
    private WxTemplateService wxTemplateService;

    @Value("${web.imgPrefixOss}")
    private String imgPrefix;

    @Value("${web.nsh_set_meal_notify_url}")
    private String nsh_set_meal_notify_url;


    /**
     * 套餐活动详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/code/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "meal/code/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String meal_qr_code = jsonRequest.containsKey("meal_qr_code") ? jsonRequest.getStr("meal_qr_code") : null;
            int meal_type = jsonRequest.containsKey("meal_type") ? jsonRequest.getInt("meal_type") : 0;
            int estateId = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            if(meal_qr_code == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该套餐不存在"),true,true);
            }

//            SetMealQrcode mealQrCode = mealQrcodeService.selectByUniqueColumn("code_num",meal_qr_code);
//            if(mealQrCode == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该套餐不存在"),true,true);
//            }

            Map<String,Object> map = new HashMap<>();
            QueryWrapper<SetMeal> qwMeal = new QueryWrapper<>();
            qwMeal.eq("meal_type",meal_type);
            qwMeal.eq("is_default",1);
            SetMeal setMeal = setMealService.getOne(qwMeal);
            if(setMeal == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该套餐活动不存在"),true,true);
            }

            if(StrUtil.isNotEmpty(setMeal.getQrCode())){
                setMeal.setQrCode(imgPrefix + setMeal.getQrCode());
            }

            if(StrUtil.isNotEmpty(setMeal.getPlayBillImg())){
                setMeal.setPlayBillImg(imgPrefix + setMeal.getPlayBillImg());
            }

            QueryWrapper<SetMealInfo> qw = new QueryWrapper<>();
            if(user_id == 1 || user_id == 24 || user_id == 263 || user_id == 329 ){

            }else{
                qw.eq("state",1);
            }
            List<SetMealInfo> infos = setMealInfoService.list(qw);
            if(CollUtil.isNotEmpty(infos)){
                for (SetMealInfo info : infos){
                    if(StrUtil.isNotEmpty(info.getInfoImg())){
                        info.setInfoImg(imgPrefix + info.getInfoImg());
                    }
                }
            }
            map.put("setMeal",setMeal);
            map.put("infos",infos);
            map.put("estate_id", 0);
            map.put("estate_name", "");
            if(user.getEstateId()!=null && user.getEstateId() > 0){
                map.put("estate_id",user.getEstateId());
                Estate estate = estateService.findById(user.getEstateId());
                if(estate!=null){
                    map.put("estate_name",estate.getEstateName());
                }
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 添加购买套餐订单
     * @param
     * @throws Exception
     */
    @PostMapping(value="/order/add")
    public JSONObject addChargerOrder(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "meal/order/add 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int meal_id = jsonRequest.containsKey("meal_id") ? jsonRequest.getInt("meal_id") : 0;
            int estate_id = jsonRequest.containsKey("estate_id") ? jsonRequest.getInt("estate_id") : 0;
            int meal_info_id = jsonRequest.containsKey("meal_info_id") ? jsonRequest.getInt("meal_info_id") : 0;
//            double money = jsonRequest.containsKey("money") ? jsonRequest.getDouble("money") : 0d;

            if(meal_info_id == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请选择充电金额"),true,true);
            }

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(user.getEstateId() == null || user.getEstateId() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请先绑定所在小区"),true,true);
            }

            SetMeal setMeal = setMealService.findById(meal_id);
            if(setMeal == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该活动不存在"), true, true);
            }

            if(setMeal.getState() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "活动未开启"), true, true);
            }

            SetMealInfo setMealInfo = setMealInfoService.findById(meal_info_id);
            if(setMealInfo == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该套餐规格不存在"), true, true);
            }

            long order_id = mealOrderService.addOrder(user, setMeal, setMealInfo);
            if (order_id > 0) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "成功", order_id), true, false);
            } else {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "失败"), true, true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     *  套餐订单列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/order/list")
    public JSONObject orderList(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "meal/order/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            List<SetMealOrder> list = mealOrderService.getMyOrderList(user_id,state,pageIndex,pageSize);
            map.put("orders",list);
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  订单详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/order/detail")
    public JSONObject orderDetail(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "meal/order/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SetMealOrder order = mealOrderService.findById(order_id);

            map.put("order",order);
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     * 消费券获取记录列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/given/record/list")
    public JSONObject givenRecordList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "meal/given/record/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            QueryWrapper<SetMealInfoGivenRecord> qw = new QueryWrapper<>();
            qw.eq("user_id",user_id);
            qw.orderByDesc("create_time");
            List<SetMealInfoGivenRecord> givenRecords = mealInfoGivenRecordService.getPageEntityList(qw,pageIndex,pageSize);
            map.put("records",givenRecords);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",givenRecords.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 调起支付
     * @return
     */
    @PostMapping(value = "/order/requestPay")
    public JSONObject requestPay(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "meal/order/requestPay 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0L;
            String subject = jsonRequest.containsKey("subject") ? jsonRequest.getStr("subject") : "";
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : null;

            String orderNo = "";
            boolean blIsMineOrder = false;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            PlatformPay platformPay = platformPayService.getDefaultAccount();
            SetMealOrder orders = mealOrderService.findById(order_id);
            if(orders != null){
                int orderUserId = orders.getUserId() ;
                if(orderUserId == user_id){
                    orderNo = orders.getOutTradeNo();
                    blIsMineOrder = true;
                }else{
                    blIsMineOrder = false;
                }

                if(orders.getStatus() == 1){//如果是 再次提交支付的话，订单号要生成新的
                    orderNo = OrderUtil.getOrderNoByTimespan();
                    if(orders.getPayType() == 1) {
                        orderNo = OrderUtil.getOrderNoByTimespan(platformPay.getSysCode());
                    }
                    orders.setOutTradeNo(orderNo);
                }else if(orders.getStatus() >= 2){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前状态不能发起支付"),true,true);
                }

                if(StrUtil.isNotEmpty(remark)){
                    orders.setRemark(remark);
                }
            }

            if(blIsMineOrder){
                String retRequest = platformPayService.appletOrder(orderNo, orders.getPayPrice(),subject,user.getOpenId(),"MEAL",nsh_set_meal_notify_url,platformPay);
                System.out.println("农商行下单返回数据: " + retRequest);
                JSONObject jsonObject = JSONUtil.parseObj(retRequest);
                if(jsonObject!=null){
                    String errCode = jsonObject.getStr("errCode");
                    String errMsg = jsonObject.getStr("errMsg");
                    if(errCode.equals("SUCCESS")){
                        JSONObject retData = jsonObject.getJSONObject("miniPayRequest");
                        retData.set("result_code","SUCCESS");
                        ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"请求成功",retData.toString()),true,false);
                        orders.setStatus(1);//支付中
                        mealOrderService.updateById(orders);
                    }else{
                        ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,errMsg),true,true);
                    }
                }
            }else{//当前订单不属于您
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 退款请求
     * @return
     */
    @PostMapping(value = "/order/refund")
    public JSONObject orderRefund(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0L;
            String reason = jsonRequest.containsKey("reason") ? jsonRequest.getStr("reason") : "";

            boolean blIsMineOrder = false;
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            PlatformPay platformPay = platformPayService.getDefaultAccount();

            SetMealOrder orders = mealOrderService.findById(order_id);
            if(orders != null){
                orders.setRefundReasonWapExplain(reason);
                if(orders.getUserId().intValue() != user_id){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单不属于你"),true,true);
                }

                if(orders.getStatus() == 7){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单在退款中请耐心等待"),true,true);
                } else if(orders.getStatus() == 8){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该订单已退款完成"),true,true);
                }

                blIsMineOrder = true;
                String out_refund_no = OrderUtil.getOrderNoByTimespan(platformPay.getSysCode());
                orders.setRefundOutTradeNo(out_refund_no);

                if(orders.getStatus() == 2){
                    if(blIsMineOrder) {
                        //String out_trade_no, BigDecimal refund_money, String out_refund_no,PlatformPay platformPay
                        String retRequest = platformPayService.refundOrder(orders.getOutTradeNo(), orders.getPayPrice(),orders.getRefundOutTradeNo(),platformPay);
                        System.out.println("retRequest: " + retRequest);
                        JSONObject jsonObject = JSONUtil.parseObj(retRequest);
                        if(jsonObject!=null){
                            String errCode = jsonObject.getStr("errCode");
                            String errMsg = jsonObject.getStr("errMsg");
                            String refundStatus = jsonObject.getStr("refundStatus");
                            if(errCode.equals("SUCCESS") && refundStatus.equals("SUCCESS")){
                                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"请求成功"),true,false);
                                orders.setStatus(7);//同意退货
                                mealOrderService.updateById(orders);
                            }else{
                                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,errMsg),true,true);
                            }
                        }
                    }else{//当前订单不属于您
                        ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
                    }
                }else{//当前订单不属于您
                    ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该状态下不能发起退款"),true,true);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 微信支付退款回调处理
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/order/refund/notify")
    public String wxPayRefundNotify(HttpServletRequest request) throws IOException {
        System.out.println("套餐活动退款  微信支付退款回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        int ret = 0;
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultXml = new String(outSteam.toByteArray(), "utf-8");
        System.out.println("套餐活动退款  微信退款处理成功回调:" + resultXml);
        Map<String, String> params = null;
        try {
            params = WXPayCommonUtil.doXMLParse(resultXml);
        } catch (JDOMException e) {
            e.printStackTrace();
        }
        outSteam.flush();
        outSteam.close();
        inStream.close();
        System.out.println("===============退款处理成功==============");
        // ------------------------------
        // 处理业务开始
        // ------------------------------
        // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
        // ------------------------------
        String return_code = params.get("return_code");
        String attach = params.get("attach");
        System.out.println("附加信息: " + attach);
        String req_info = params.get("req_info");
        try {
            if(return_code.equals("SUCCESS")){
                String descrypt = "";//RSA.descrypt(req_info,api_key);
                Map<String,String> reqInfoMap = WXPayCommonUtil.doXMLParse(descrypt);
                ret = refund_success_setmeal(reqInfoMap,1);
                if(ret > 0){
                    return "success";
                }else{
                    return "fail";
                }
            }
            return "fail";
        }
//        catch (NoSuchPaddingException e) {
//            e.printStackTrace();
//        }
//        catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (NoSuchProviderException e) {
//            e.printStackTrace();
//        } catch (InvalidKeyException e) {
//            e.printStackTrace();
//        } catch (BadPaddingException e) {
//            e.printStackTrace();
//        } catch (IllegalBlockSizeException e) {
//            e.printStackTrace();
//        }
        catch (Exception e) {
            e.printStackTrace();
        }
        // 处理业务完毕
        // ------------------------------
        return "fail";
    }

    /**
     * 商品订单的 退款成功处理
     * @param params
     * @return
     */
    @SuppressWarnings("unchecked")
    private int refund_success_setmeal(Map<String, String> params,int payType){
        String out_trade_no = params.get("out_trade_no");// 本平台  商户订单号
        int ret = 0;
        try{
            QueryWrapper<SetMealOrder> qw = new QueryWrapper<>();
            qw.eq("out_trade_no",out_trade_no).or().eq("order_no",out_trade_no);
            SetMealOrder order = mealOrderService.getOne(qw);
            if(order != null){
                User user = userService.findById(order.getUserId());
                if(order.getStatus() == 7) {//发起退款 并同意申请 的才执行
                    String refund_fee = "";//  订单金额
                    String trade_no = "";//  订单号
                    double refund_fee_double = 0;

//                    refund_fee = params.get("refund_fee");
//                    trade_no = params.get("transaction_id");//微信支付订单号
//                    refund_fee_double = Double.valueOf(refund_fee) / 100;


                    if (payType == 0) {//支付宝支付参数
                        refund_fee = params.get("refund_fee");
                        trade_no = params.get("transaction_id");//微信支付订单号
                        refund_fee_double = Double.valueOf(refund_fee) / 100;
                    } else if (payType == 1) {//微信支付参数
                        refund_fee = params.get("refund_fee");
                        trade_no = params.get("transaction_id");//微信支付订单号
                        refund_fee_double = Double.valueOf(refund_fee) / 100;
                    } else if (payType == 2) {// 农商行 支付参数
                        refund_fee = params.get("refundAmount");
                        refund_fee_double = Double.valueOf(refund_fee) / 100;
                        trade_no = params.get("targetOrderId");//微信支付订单号
                    }

                    //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
                    // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                    order.setStatus(8);
                    order.setRefundStatus(2);
                    order.setTransactionId(trade_no);
                    order.setRefundPrice(new BigDecimal(refund_fee_double));
                    order.setRefundReasonTime(new Date());
                    boolean bl = mealOrderService.updateById(order);
                    if(bl){
                        //退款成功通知
                        wxTemplateService.sendWxMsgRefundSetMeal(user,order,4);
                    }

                    // 添加 微信支付的 动账记录
                    WxPayTransaction transaction = new WxPayTransaction();
                    transaction.setEstateId(order.getEstateId());
//                    transaction.setEstateName(order.getEstateName());
                    transaction.setPayType(payType);// 0 -微信支付
                    transaction.setTransactionId(trade_no);
                    transaction.setUserId(user.getId());
                    transaction.setFeeType("set_meal_refund");
                    transaction.setTotalMoney(new BigDecimal(refund_fee_double));
                    transaction.setOutTradeNo(out_trade_no);
                    if(StrUtil.isNotEmpty(user.getNickName())){
                        transaction.setNickName(EmojiParser.parseToAliases(user.getNickName()));
                    }
                    transaction.setCreateTime(new Date());
                    transaction.setInOrOut(0);//动账  0 - 出账 1 - 进账
                    transaction.setRemark("套餐活动的退款");
                    transaction.setPayPlatformId(order.getPayPlatformId());
                    payTransactionService.save(transaction);
                    System.out.println("=====支付成功====");
                    logger.info("套餐活动订单号：" + out_trade_no + "支付成功");
                }
            }else{
                System.out.println("普通商品订单号：" + out_trade_no + "不存在");
                logger.error("普通商品订单号：" + out_trade_no + "不存在");
            }
        }catch (Exception ex){
            ex.printStackTrace();
            System.out.println(ex.getMessage());
        }
        return ret;
    }


}
